<template>
  <el-dialog :destroy-on-close="true" :lock-scroll="false" title="分配" :visible.sync="visible" width="950px"
             :before-close="cancel">
    <el-alert
      title="请先选择出库仓库，再选择配件"
      type="warning"
      style="margin-bottom: 16px"
      show-icon>
    </el-alert>
    <el-form ref="form" :model="form" label-width="auto" :rules="rules">
      <el-form-item label="出库仓库：" prop="warehouse_id">
        <WarehouseSelect :astrict="1" v-model="form.warehouse_id" placeholder="请选择入库仓库"/>
      </el-form-item>
      <el-form-item label="目标用户：" prop="user_id">
        <PrincipalSelect ref="principalSelectRef" placeholder="请选择目标用户" v-model="form.user_id"/>
      </el-form-item>
      <el-form-item prop="description" label="备注：">
        <el-input v-model="form.description" placeholder="请输入备注" type="textarea" :rows="5"/>
      </el-form-item>
      <editTable :warehouseId="this.form.warehouse_id" :table.sync="form.items" ref="editTableRef"></editTable>
    </el-form>
    <div slot="footer">
      <el-button @click="cancel">取消</el-button>
      <el-button :loading="loading" type="primary" @click="save('form')">保存</el-button>
    </div>
  </el-dialog>
</template>

<script>
import editTable from "./EditTable.vue";
import WarehouseSelect from "@/views/bom/stock/components/WarehouseSelect.vue";
import PrincipalSelect from "@/views/project/task/components/PrincipalSelect.vue";

export default {
  components: {PrincipalSelect, WarehouseSelect, editTable},
  props: {
    // 修改回显的数据
    data: Object
  },
  data() {
    return {
      visible: false,
      loading: false,
      // 表单数据
      form: {
        warehouse_id: null,
        user_id: null,
        description: null,
        items: [],
      },
      rules: {
        warehouse_id: [
          {required: true, message: '请选择入库仓库', trigger: 'blur'},
        ],
        user_id: [
          {required: true, message: '请选择入目标用户', trigger: 'blur'},
        ],
      },
    }
  },
  methods: {
    active() {
      this.visible = true;
    },
    cancel() {

      this.$refs.form.resetFields()
      console.log(this.form)
      this.visible = false;
      this.loading = false
    },
    /*提交*/
    save(formName) {
      let flag = false, flag2 = false
      this.$refs[formName].validate((valid) => {
        flag = valid
      });
      flag2 = this.$refs.editTableRef.validate()
      if (flag && flag2) {
        const form = JSON.parse(JSON.stringify(this.form))
        form.items = form.items.map(({id, quantity}) => ({id, quantity}))
        this.handlePostForm(form)
      }
    },

    async handlePostForm(form) {
      this.loading = true
      const res = (await this.$http.post('/inventories_allocation', form)).data
      res.code === 0 ? this.$message.success(res.msg) : this.$message.error(res.msg)
      this.$emit('reload')
      this.cancel()
    },
  }
}
</script>

<style lang="scss" scoped>
.el-select {
  width: 100%;
}
</style>
